package net.oschina.app.ui;

import net.oschina.app.AppContext;
import net.oschina.app.AppException;
import net.oschina.app.R;
import net.oschina.app.bean.Notice;
import net.oschina.app.common.UIHelper;
import net.oschina.app.common.UpdateManager;
import net.oschina.app.ui.fragments.ActiveViewPagerFragment;
import net.oschina.app.ui.fragments.BaseMainViewPagerFragment;
import net.oschina.app.ui.fragments.NewsViewPagerFragment;
import net.oschina.app.ui.fragments.QuestionViewPagerFragment;
import net.oschina.app.ui.fragments.SoftwareLibViewPageFragment;
import net.oschina.app.ui.fragments.TweetViewPagerFragment;
import uk.co.senab.actionbarpulltorefresh.extras.actionbarcompat.PullToRefreshAttacher;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.support.v7.app.ActionBar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;

public class MainFragmentActivity extends BaseSlidingFragmentActivity {

	private PullToRefreshAttacher mPullToRefreshAttacher;
	private ActionBar mActionBar;
	private AppContext appContext;// 全局Context
	private MenuListFragment mFrag;
	private MainReceiver mainReceiver;// 动弹发布接收器

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initSlidingMenu();
		initActionBar();

		// 注册广播接收器
		mainReceiver = new MainReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("net.oschina.app.action.LOGIN");
		filter.addAction("net.oschina.app.action.APPWIDGET_UPDATE");
		registerReceiver(mainReceiver, filter);

		appContext = (AppContext) getApplication();
		// 网络连接判断
		if (!appContext.isNetworkConnected())
			UIHelper.ToastMessage(this, R.string.network_not_connected);
		// 初始化登录
		appContext.initLoginInfo();
		// 检查新版本
		if (appContext.isCheckUp()) {
			UpdateManager.getUpdateManager().checkAppUpdate(this, false);
		}

		setBehindContentView(R.layout.frame_menu);
		setContentView(R.layout.frame_main);
		FragmentTransaction t = this.getSupportFragmentManager()
				.beginTransaction();
		mFrag = new MenuListFragment();
		t.replace(R.id.frame_menu, mFrag);
		t.commit();

		t = this.getSupportFragmentManager().beginTransaction();
		NewsViewPagerFragment nFrag = new NewsViewPagerFragment(this, 0);
		t.replace(R.id.frame_main, nFrag);
		t.commit();

		mPullToRefreshAttacher = PullToRefreshAttacher.get(this);

		// 启动轮询通知信息
		this.foreachUserNotice();
	}

	private void initActionBar() {
		mActionBar = getSupportActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true);
		mActionBar.setHomeButtonEnabled(true);
		mActionBar.setTitle(R.string.head_title_news);
	}

	private void initSlidingMenu() {
		// customize the SlidingMenu
		SlidingMenu sm = getSlidingMenu();
		sm.setShadowWidthRes(R.dimen.shadow_width);
		sm.setShadowDrawable(R.drawable.shadow);
		sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
		sm.setFadeDegree(0.35f);
		sm.setMode(SlidingMenu.LEFT);
		sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
	}

	public class MenuListFragment extends ListFragment implements
			OnItemClickListener {
		private int[] imageArray = new int[] { R.drawable.main_menu_news,
				R.drawable.main_menu_question, R.drawable.main_menu_tweet,
				R.drawable.main_menu_home, R.drawable.main_menu_login_logout,
				R.drawable.main_menu_user_info, R.drawable.main_menu_software,
				R.drawable.main_menu_search, R.drawable.main_menu_setting,
				R.drawable.main_menu_exit };
		private int[] titleArray = new int[] { R.string.head_title_news,
				R.string.head_title_question, R.string.head_title_tweet,
				R.string.head_title_my, R.string.main_menu_login,
				R.string.main_menu_myinfo, R.string.main_menu_software,
				R.string.main_menu_search, R.string.main_menu_setting,
				R.string.main_menu_exit };
		private int[] msgCountArray = new int[titleArray.length];
		
		public void onActivityCreated(Bundle savedInstanceState) {
			super.onActivityCreated(savedInstanceState);
			showMainMenuList();
		}

		private void showMainMenuList() {
			if (appContext.isLogin()) {
				titleArray[4] = R.string.main_menu_logout;
			} else {
				titleArray[4] = R.string.main_menu_login;
			}
			MenuListViewAdapter adapter = new MenuListViewAdapter(getActivity());
			setListAdapter(adapter);
			getListView().setOnItemClickListener(this);
		}

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			FragmentManager supportFragmentManager = getSupportFragmentManager();
			BaseMainViewPagerFragment baseFragment = (BaseMainViewPagerFragment) supportFragmentManager
					.findFragmentById(R.id.frame_main);
			if (baseFragment == null || baseFragment.getPosition() != position) {
				if (position < 4) {
					FragmentTransaction t = supportFragmentManager
							.beginTransaction();
					switch (position) {
					case 0:
						t.replace(R.id.frame_main, new NewsViewPagerFragment(
								MainFragmentActivity.this, position));
						mActionBar.setTitle(titleArray[position]);
						break;
					case 1:
						t.replace(R.id.frame_main,
								new QuestionViewPagerFragment(
										MainFragmentActivity.this, position));
						mActionBar.setTitle(titleArray[position]);
						break;
					case 2:
						t.replace(R.id.frame_main, new TweetViewPagerFragment(
								MainFragmentActivity.this, position));
						mActionBar.setTitle(titleArray[position]);
						break;
					case 3:
						t.replace(R.id.frame_main, new ActiveViewPagerFragment(
								MainFragmentActivity.this, position));
						mActionBar.setTitle(titleArray[position]);
						break;
					}
					t.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
					t.commit();
				} else {
					switch (position) {
					case 4:// 用户登录-注销
						UIHelper.loginOrLogout(MainFragmentActivity.this);
						break;
					case 5:// 我的资料
						UIHelper.showUserInfo(MainFragmentActivity.this);
						break;
					case 6:// 开源软件
						FragmentTransaction t = supportFragmentManager
								.beginTransaction();
						t.replace(R.id.frame_main,
								new SoftwareLibViewPageFragment(
										MainFragmentActivity.this, position));
						mActionBar.setTitle(titleArray[position]);
						t.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
						t.commit();
						// UIHelper.showSoftware(MainFragmentActivity.this);
						break;
					case 7:// 搜索
						UIHelper.showSearch(MainFragmentActivity.this);
						break;
					case 8:// 设置
						UIHelper.showSetting(MainFragmentActivity.this);
						break;
					case 9:// 退出
						UIHelper.Exit(MainFragmentActivity.this);
					default:
						break;
					}
				}
			}
			showContent();
		}

		private class MenuListViewAdapter extends BaseAdapter {
			private Context context;

			public MenuListViewAdapter(Context context) {
				this.context = context;
			}

			@Override
			public int getCount() {
				return imageArray.length;
			}

			@Override
			public Object getItem(int position) {
				return null;
			}

			@Override
			public long getItemId(int position) {
				return position;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				ViewHolder viewHolder = null;
				if (convertView == null) {
					convertView = LayoutInflater.from(context).inflate(
							R.layout.main_menu_item, null);
					viewHolder = new ViewHolder();
					viewHolder.icon = (ImageView) convertView.findViewById(R.id.main_menu_icon);
					viewHolder.title = (TextView) convertView.findViewById(R.id.main_menu_title);
					viewHolder.msgCount = (TextView) convertView.findViewById(R.id.main_menu_msg_count);
					convertView.setTag(viewHolder);
				} else {
					viewHolder = (ViewHolder)convertView.getTag();
				}
				viewHolder.icon.setImageResource(imageArray[position]);
				viewHolder.title.setText(titleArray[position]);
				if(msgCountArray[position] > 0) {
					viewHolder.msgCount.setText(String.valueOf(msgCountArray[position]));
					viewHolder.msgCount.setVisibility(View.VISIBLE);
				} else {
					viewHolder.msgCount.setVisibility(View.GONE);
				}
				return convertView;
			}
			private class ViewHolder {
				public ImageView icon;
				public TextView title;
				public TextView msgCount;
			}
		}
	}

	public PullToRefreshAttacher getPullToRefreshAttacher() {
		return mPullToRefreshAttacher;
	}

	public void setActionBarSubtitle(String subtitle) {
		mActionBar.setSubtitle(subtitle);
	}

	/**
	 * 轮询通知信息
	 */
	private void foreachUserNotice() {
		final int uid = appContext.getLoginUid();
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				if (msg.what == 1) {
					UIHelper.sendBroadCast(MainFragmentActivity.this,
							(Notice) msg.obj);
				}
				foreachUserNotice();// 回调
			}
		};
		new Thread() {
			public void run() {
				Message msg = new Message();
				try {
					sleep(60 * 1000);
					if (uid > 0) {
						Notice notice = appContext.getUserNotice(uid);
						msg.what = 1;
						msg.obj = notice;
					} else {
						msg.what = 0;
					}
				} catch (AppException e) {
					e.printStackTrace();
					msg.what = -1;
				} catch (Exception e) {
					e.printStackTrace();
					msg.what = -1;
				}
				handler.sendMessage(msg);
			}
		}.start();
	}

	public class MainReceiver extends BroadcastReceiver {

		private final static int NOTIFICATION_ID = R.string.app_name;
		private int lastNoticeCount;

		@Override
		public void onReceive(Context context, Intent intent) {
			String ACTION_NAME = intent.getAction();
			if (ACTION_NAME.equals("net.oschina.app.action.LOGIN")) {
				if (mFrag != null && mFrag.isResumed()) {
					mFrag.showMainMenuList();
				}

			} else if ("net.oschina.app.action.APPWIDGET_UPDATE"
					.equals(ACTION_NAME)) {
				int atmeCount = intent.getIntExtra("atmeCount", 0);// @我
				int msgCount = intent.getIntExtra("msgCount", 0);// 留言
				int reviewCount = intent.getIntExtra("reviewCount", 0);// 评论
				int newFansCount = intent.getIntExtra("newFansCount", 0);// 新粉丝
				int activeCount = atmeCount + reviewCount + msgCount
						+ newFansCount;// 信息总数

				// 动态-总数
				if (Main.bv_active != null) {
					if (activeCount > 0) {
						Main.bv_active.setText(activeCount + "");
						Main.bv_active.show();
					} else {
						Main.bv_active.setText("");
						Main.bv_active.hide();
					}
				}
				// @我
				if (Main.bv_atme != null) {
					if (atmeCount > 0) {
						Main.bv_atme.setText(atmeCount + "");
						Main.bv_atme.show();
					} else {
						Main.bv_atme.setText("");
						Main.bv_atme.hide();
					}
				}
				// 评论
				if (Main.bv_review != null) {
					if (reviewCount > 0) {
						Main.bv_review.setText(reviewCount + "");
						Main.bv_review.show();
					} else {
						Main.bv_review.setText("");
						Main.bv_review.hide();
					}
				}
				// 留言
				if (Main.bv_message != null) {
					if (msgCount > 0) {
						Main.bv_message.setText(msgCount + "");
						Main.bv_message.show();
					} else {
						Main.bv_message.setText("");
						Main.bv_message.hide();
					}
				}

				// 通知栏显示
				this.notification(context, activeCount);
			}
		}

		private void notification(Context context, int noticeCount) {
			// 创建 NotificationManager
			NotificationManager notificationManager = (NotificationManager) context
					.getSystemService(Context.NOTIFICATION_SERVICE);

			String contentTitle = "开源中国";
			String contentText = "您有 " + noticeCount + " 条最新信息";
			int _lastNoticeCount;

			// 判断是否发出通知信息
			if (noticeCount == 0) {
				notificationManager.cancelAll();
				lastNoticeCount = 0;
				return;
			} else if (noticeCount == lastNoticeCount) {
				return;
			} else {
				_lastNoticeCount = lastNoticeCount;
				lastNoticeCount = noticeCount;
			}

			// 创建通知 Notification
			Notification notification = null;

			if (noticeCount > _lastNoticeCount) {
				String noticeTitle = "您有 " + (noticeCount - _lastNoticeCount)
						+ " 条最新信息";
				notification = new Notification(R.drawable.icon, noticeTitle,
						System.currentTimeMillis());
			} else {
				notification = new Notification();
			}

			// 设置点击通知跳转
			Intent intent = new Intent(context, Main.class);
			intent.putExtra("NOTICE", true);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NEW_TASK);

			PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
					intent, PendingIntent.FLAG_UPDATE_CURRENT);

			// 设置最新信息
			notification.setLatestEventInfo(context, contentTitle, contentText,
					contentIntent);

			// 设置点击清除通知
			notification.flags = Notification.FLAG_AUTO_CANCEL;

			if (noticeCount > _lastNoticeCount) {
				// 设置通知方式
				notification.defaults |= Notification.DEFAULT_LIGHTS;

				// 设置通知音-根据app设置是否发出提示音
				if (((AppContext) context.getApplicationContext()).isAppSound())
					notification.sound = Uri.parse("android.resource://"
							+ context.getPackageName() + "/"
							+ R.raw.notificationsound);

				// 设置振动 <需要加上用户权限android.permission.VIBRATE>
				// notification.vibrate = new long[]{100, 250, 100, 500};
			}

			// 发出通知
			notificationManager.notify(NOTIFICATION_ID, notification);
		}

	}

}
